package com.flaremars.picker.fragments;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.flaremars.picker.PreTreatmentActivity;
import com.flaremars.picker.R;
import com.flaremars.picker.constants.PreferencesConstants;
import com.flaremars.picker.utils.BitmapUtils;
import com.flaremars.picker.utils.DrawingManager;
import com.flaremars.picker.utils.FileUtils;
import com.flaremars.picker.utils.PreferencesUtils;
import com.flaremars.picker.utils.ScreenUtils;
import com.flaremars.picker.widget.DrawingView;

import java.io.File;
import java.io.IOException;


public class PicturePreTreatmentFragment extends Fragment {

    private static final int DEFAULT_ERASER_SIZE_POSITION = 1;
    private static final String TAG = "PreTreatmentFragment";

    private ImageView imageMainContent;
    private Button btnCancel;
    private Button btnRestore;
    private Spinner eraserSizeSpinner;
    private DrawingView drawingView;
    private String picturePath;
    private boolean needRotate;

    public static PicturePreTreatmentFragment newFragment(String picturePath,boolean needRotate) {
        int dotIndex= picturePath.lastIndexOf('.');
        assert dotIndex != -1;
        String newPath = new StringBuffer(picturePath).insert(dotIndex,"_pretreatment").toString();
        try {
            FileUtils.INSTANCE.copyFile(picturePath,newPath);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        PicturePreTreatmentFragment fragment = new PicturePreTreatmentFragment();
        Bundle arguments = new Bundle();
        arguments.putString(PreTreatmentActivity.ARGUMENT_PICTURE_PATH,newPath);
        arguments.putBoolean(PreTreatmentActivity.ARGUMENT_NEED_ROTATE,needRotate);
        fragment.setArguments(arguments);
        return fragment;
    }

    public PicturePreTreatmentFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        picturePath = getArguments().getString(PreTreatmentActivity.ARGUMENT_PICTURE_PATH);
        needRotate = getArguments().getBoolean(PreTreatmentActivity.ARGUMENT_NEED_ROTATE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_picture_pretreatment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViews(view);
        initViews();
        initDrawingView();
        doPreTreatment();
    }

    private void findViews(View parent) {
        imageMainContent = (ImageView) parent.findViewById(R.id.iv_image_content);
        btnCancel = (Button) parent.findViewById(R.id.btn_cancel);
        btnRestore = (Button) parent.findViewById(R.id.btn_restore);
        drawingView = (DrawingView) parent.findViewById(R.id.drawingview);
        eraserSizeSpinner = (Spinner) parent.findViewById(R.id.spinner_eraser_size);
    }

    private void initViews() {
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawingView.cancel();
            }
        });
        btnRestore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawingView.restore();
            }
        });
        eraserSizeSpinner.setSelection(DEFAULT_ERASER_SIZE_POSITION);
        eraserSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                drawingView.setEraseSize(position * 10 + 10);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initDrawingView() {
        Point screenSize = ScreenUtils.INSTANCE.getScreenSize(getContext());
        int width = screenSize.x;
        int height =  screenSize.y -
                ScreenUtils.INSTANCE.dp2px(getContext(),50) -
                ScreenUtils.INSTANCE.getActionBarHeight(getContext()) -
                ScreenUtils.INSTANCE.getStatusBarHeight(getContext());

        drawingView.setViewSize(width, height);
        DrawingManager.INSTANCE.setDrawingRegion(new Rect(0,0,width,height));
    }

    private void doPreTreatment() {
        File targetFile = new File(picturePath);
        if (targetFile.exists()) {
            imageMainContent.setVisibility(View.VISIBLE);
            showStatus("#0:预处理开始");
            new PictureProcessTask().execute();
        } else {
            showStatus("目标图片不存在");
        }
    }

    //图片缩放处理
    private Bitmap doScale() {

        showStatus("#1:进行缩放处理");
        int requestWidth = PreferencesUtils.INSTANCE.getInteger(getContext(), PreferencesConstants.SETTINGS_REQUEST_WIDTH);
        int requestHeight = PreferencesUtils.INSTANCE.getInteger(getContext(), PreferencesConstants.SETTINGS_REQUEST_HEIGHT);
        int requestSize = 300;
        return BitmapUtils.INSTANCE.scaleImage(picturePath, requestHeight, requestWidth, requestSize);
    }

    //图片旋转处理
    private Bitmap doRotate(Bitmap src) {

        if (needRotate) {
            showStatus("#2:进行旋转处理");
            return BitmapUtils.INSTANCE.adjustPhotoRotation(src, 90);
        } else {
            showStatus("#2:不进行旋转处理");
            return src;
        }
    }

    //图片边缘提取
    private Bitmap doCannyEdge(Bitmap src) {

        showStatus("#3:进行canny算法边缘提取");
        return BitmapUtils.INSTANCE.cannyEdgeProcess(src);
    }

    private class PictureProcessTask extends AsyncTask<Void,Bitmap,Bitmap> {

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap bmpTemp = doScale();
            bmpTemp = doRotate(bmpTemp);
            publishProgress(bmpTemp);
            bmpTemp = doCannyEdge(bmpTemp);
            return bmpTemp;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            showStatus("预处理结束");
            try {
                BitmapUtils.INSTANCE.saveBitmapToFile(bitmap,picturePath, Bitmap.CompressFormat.JPEG);
            } catch (IOException e) {
                e.printStackTrace();
            }
            switchEditMode();
        }

        @Override
        protected void onProgressUpdate(Bitmap... values) {
            super.onProgressUpdate(values);
            imageMainContent.setImageBitmap(values[0]);
        }
    }

    private void switchEditMode(String curPicturePath) {
        imageMainContent.setVisibility(View.GONE);
        drawingView.setVisibility(View.VISIBLE);
        drawingView.setBitmap(BitmapFactory.decodeFile(curPicturePath));
    }

    private void switchEditMode() {
        switchEditMode(picturePath);
    }

    public String saveBitmap() throws IOException {
        Bitmap result = drawingView.getBitmap();
        BitmapUtils.INSTANCE.saveBitmapToFile(result,picturePath, Bitmap.CompressFormat.JPEG);
        return picturePath;
    }

    private void toastMessage(String msg) {
        Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
    }

    private void showStatus(String msg) {
        Log.d(TAG,msg);
    }
}
